package com.bw.visitor_module.visitor

import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.CompoundButton
import android.widget.ImageView
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.bw.visitor_module.R
import com.bw.visitor_module.databinding.ActivityVisitorBinding
import com.bw.visitor_module.visitor.entity.CarEntity
import com.bw.visitor_module.visitor.entity.ParkingValueEntity
import com.bw.visitor_module.visitor.entity.VisitorEntity
import com.google.gson.Gson
import com.kf.common.entity.EventBusEntity
import com.kf.common.mvi.view.BaseActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.text.SimpleDateFormat
import java.util.*

@Route(path = "/visitor/visitoractivity")
class VisitorActivity : BaseActivity<ActivityVisitorBinding, VisitorViewModel>(),
    View.OnClickListener {

    var simpleDateFormat = SimpleDateFormat("MM月dd日")//时间转换器
    var simpleDate = SimpleDateFormat("yyyy-MM-dd")
    var parkingEntity= ParkingValueEntity()

    override fun createViewModel(): VisitorViewModel {
        return viewModels<VisitorViewModel>().value
    }

    override fun createViewBind(): ActivityVisitorBinding {
        return ActivityVisitorBinding.inflate(inflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        BarUtils.setStatusBarColor(this, Color.parseColor("#2196F3"))
        initView()
        mViewModel.requestDept()
        initClick()
        initBind()
        EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    private fun initView() {
        var currentTimeMillis = System.currentTimeMillis()
        var format = simpleDate.format(currentTimeMillis)
        mView.visitorData.setText(format)
        mView.visitorName.setText(SPUtils.getInstance().getString("userName", "hxw"))
    }

    private fun initBind() {
        lifecycleScope.launch(Dispatchers.Main) {
            mViewModel.mutableContainer.uiStateFlow.collect {
                if (it != null && it!!.deptEntity != null) {
                    if (it.deptEntity!!.statuesCode == 200) {
                        mView.visitorDept.setText(it!!.deptEntity!!.values!!.get(0).departmentName)
                    }
                }

                if (it != null && it!!.visitorEntity != null) {
                    if (it.visitorEntity!!.statuesCode == 200) {
                        finish()
                    }
                }

            }
        }
    }

    private fun initClick() {
        mView.visitorBack.setOnClickListener(this)
        mView.visitorStartTime.setOnClickListener(this)
        mView.visitorEndTime.setOnClickListener(this)
        mView.visitorCommit.setOnClickListener(this)
        mView.visitorCar.setOnClickListener(this)
        mView.visitorSwitch.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked)
                mView.visitorLinear.visibility = View.VISIBLE
            else
                mView.visitorLinear.visibility = View.GONE
        }
    }

    private var startTime = System.currentTimeMillis()
    private var endTime = System.currentTimeMillis()
    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.visitor_back -> {
                finish()
            }
            R.id.visitor_start_time -> {
                TimePickerBuilder(this, object : OnTimeSelectListener {
                    override fun onTimeSelect(date: Date?, v: View?) {
                        var format = simpleDateFormat.format(date)
                        startTime = date!!.time
                        var substring = format.substring(0, 2)
                        var substrings = format.substring(3, 5)
                        if (substring.toInt() < 10)
                            substring = substring.removeRange(0, 1)
                        if (substrings.toInt() < 10)
                            substrings = substrings.removeRange(0, 1)
                        mView.visitorStartTime.setText("${substring}月${substrings}日")
                    }
                }).build().show()
            }
            R.id.visitor_end_time -> {
                TimePickerBuilder(this, object : OnTimeSelectListener {
                    override fun onTimeSelect(date: Date?, v: View?) {
                        var format = simpleDateFormat.format(date)
                        endTime = date!!.time
                        var substring = format.substring(0, 2)
                        var substrings = format.substring(3, 5)
                        if (substring.toInt() < 10)
                            substring = substring.removeRange(0, 1)
                        if (substrings.toInt() < 10)
                            substrings = substrings.removeRange(0, 1)
                        mView.visitorEndTime.setText("${substring}月${substrings}日")
                    }
                }).build().show()
            }
            R.id.visitor_commit -> {
                if (mView.visitorStartTime.text.equals("选择开始日期")) {
                    ToastUtils.showShort("请选择开始日期")
                    return
                }
                if (mView.visitorEndTime.text.equals("选择结束日期")) {
                    ToastUtils.showShort("请选择结束日期")
                    return
                }
                if (mView.visitorSwitch.isChecked) {
                    if (TextUtils.isEmpty(mView.visitorNumber.text.toString())) {
                        ToastUtils.showShort("请输入车牌号")
                        return
                    }
                    if (mView.visitorCar.text.toString().equals("临时车位")) {
                        ToastUtils.showShort("请选择车位停放车")
                        return
                    }
                }
                if (TextUtils.isEmpty(mView.visitorMessage.text.toString())) {
                    ToastUtils.showShort("请输入申请原因")
                    return
                }
                var visitorEntity = VisitorEntity()
                visitorEntity.carNum = mView.visitorNumber.text.toString()
                visitorEntity.parkId = parkingEntity.parkId
                visitorEntity.userId = SPUtils.getInstance().getInt("userId", -1)
                visitorEntity.visitorDescribe = mView.visitorMessage.text.toString()
                visitorEntity.visitorEnd = endTime.toString()
                visitorEntity.visitorStart = startTime.toString()
                visitorEntity.visitorTime = System.currentTimeMillis().toString()
                visitorEntity.parkName = parkingEntity.parkName

                var carEntity = CarEntity()
                carEntity.carNum = mView.visitorNumber.text.toString()
                carEntity.colorId = 86
                carEntity.parkId = parkingEntity.parkId
                if (mView.visitorSwitch.isChecked){
                    mViewModel.requestCar(carEntity,visitorEntity)
                }else{
                    mViewModel.requestVisitorUnCar(visitorEntity)
                }
            }
            R.id.visitor_car -> {
                ARouter.getInstance().build("/parking/parkingactivity")
                    .withString("action", "visitor").navigation(this, 200)
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun visitorThread(eventBusEntity: EventBusEntity) {
        parkingEntity = GsonUtils.fromJson(
            eventBusEntity.map!!.get("parkEntity").toString(),
            ParkingValueEntity::class.java
        )
        mView.visitorCar.setText("${parkingEntity.parkId}号车位")
    }
}